package org.towson.forensics;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.ContactsContract.Contacts;
import android.util.Log;

public class ContactsHelper {
	static ContentResolver cr;
	public ContactsHelper(Context context) {
		super();
		this.cr = context.getContentResolver();
	}
	Uri myContact = ContentUris.withAppendedId(Contacts.CONTENT_URI, 1);
	public void getContacts(){
		Cursor c = cr.query(Contacts.CONTENT_URI, null, null, null, Contacts.DISPLAY_NAME);
		FileOutputStream os = writeFile("contacts.txt");
		if (c.moveToFirst() && os != null){
			try{
				do{
				os.write(Contacts.DISPLAY_NAME.getBytes());
				}while(c.moveToNext());
				os.close();
			
			} catch (IOException e) {
				Log.w("ExternalStorage", "Error writing" + Contacts.DISPLAY_NAME, e);
			}
		}
	}
	
	public FileOutputStream writeFile(String filename){
		String state = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED.equals(state)){
			//we can read and write the media
			File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
			File file = new File(path, filename);
			try {
				path.mkdirs();  //directory exists
				FileOutputStream os = new FileOutputStream(file);
				return os;
			} catch (IOException e) {
				Log.w("ExternalStorage", "Error writing" + file, e);
			}
		}
		return null;
	}

}
